"""
配置管理
支持不同环境的数据库配置
"""

import os

from pydantic_settings import BaseSettings


class Settings(BaseSettings):
    """应用程序配置"""

    # 应用程序设置
    app_name: str = "Allhome API"
    app_version: str = "0.1.0"
    debug: bool = False

    # 数据库配置
    database_url: str = "sqlite+aiosqlite:///./allhome.db"

    # MySQL 配置 (可选)
    mysql_host: str | None = None
    mysql_port: int = 3306
    mysql_user: str | None = None
    mysql_password: str | None = None
    mysql_database: str | None = None

    # SQLite 配置 (可选)
    sqlite_path: str = "./allhome.db"

    # 安全配置
    secret_key: str = "your-secret-key-change-in-production"
    algorithm: str = "HS256"
    access_token_expire_minutes: int = 30

    # CORS 配置
    cors_origins: str = "*"

    model_config = {"env_file": ".env", "case_sensitive": False}

    @property
    def mysql_url(self) -> str | None:
        """构建 MySQL 连接 URL"""
        if all(
            [self.mysql_host, self.mysql_user, self.mysql_password, self.mysql_database]
        ):
            return f"mysql+aiomysql://{self.mysql_user}:{self.mysql_password}@{self.mysql_host}:{self.mysql_port}/{self.mysql_database}"
        return None

    @property
    def sqlite_url(self) -> str:
        """构建 SQLite 连接 URL"""
        return f"sqlite+aiosqlite:///{self.sqlite_path}"

    def get_database_url(self) -> str:
        """获取当前环境的数据库 URL"""
        # 优先使用环境变量中的数据库 URL
        env_db_url = os.getenv("DATABASE_URL")
        if env_db_url:
            return env_db_url

        # 如果指定了 MySQL 配置,使用 MySQL
        if self.mysql_url:
            return self.mysql_url

        # 默认使用 SQLite
        return self.sqlite_url


# 创建全局配置实例
settings = Settings()


# 数据库配置
DATABASE_URL = settings.get_database_url()

# 根据数据库类型设置不同的连接参数
if DATABASE_URL.startswith("mysql"):
    # MySQL 特定配置
    ECHO_SQL = settings.debug
    POOL_SIZE = 10
    MAX_OVERFLOW = 20
    POOL_TIMEOUT = 30
    POOL_RECYCLE = 3600
elif DATABASE_URL.startswith("sqlite"):
    # SQLite 特定配置
    ECHO_SQL = settings.debug
    POOL_SIZE = 5
    MAX_OVERFLOW = 10
    POOL_TIMEOUT = 30
    POOL_RECYCLE = 3600
else:
    # 默认配置
    ECHO_SQL = settings.debug
    POOL_SIZE = 5
    MAX_OVERFLOW = 10
    POOL_TIMEOUT = 30
    POOL_RECYCLE = 3600
